package base

import (
	"Web-Shop/models"
	"Web-Shop/modules/utils"
	moUtils "Web-Shop/modules/utils"
	"strconv"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
)

type BaseController struct {
	beego.Controller
	User    *models.User
	IsLogin bool
}

func init() {
	beego.AddFuncMap("ConnStr", ConnStr)
	beego.ErrorController(&BaseController{})
}

func (c *BaseController) Prepare() {
	userName := c.GetSession("userName")
	if userName == nil {
		userName = moUtils.DeBase64(c.Ctx.GetCookie("userName"))
	}
	if userName != "" {
		c.User = &models.User{
			Name: userName.(string),
		}
		if err := c.User.Read("Name"); err != nil {
			c.IsLogin = false
		} else {
			c.IsLogin = true
		}
	}
	c.Data["IsLogin"] = c.IsLogin
	c.Data["User"] = c.User
}

func (c *BaseController) FlashNotice(msg string, args ...interface{}) {
	flash := beego.NewFlash()
	if len(args) > 0 {
		flash.Notice(msg, args)
	} else {
		flash.Notice(msg)
	}
	flash.Store(&c.Controller)
}

func (c *BaseController) SetPaginator(per int, nums int64) *utils.Paginator {
	p := utils.NewPaginator(c.Ctx.Request, per, nums)
	c.Data["paginator"] = p
	return p
}

func (b *BaseController) SetObjects(qs orm.QuerySeter, objects interface{}) error {
	return b.SetObjectsWithLimit(qs, objects, 20)
}

func (b *BaseController) SetObjectsWithLimit(qs orm.QuerySeter, objects interface{}, per int) error {
	cnt, err := qs.Count()
	if err != nil {
		return err
	}
	// create paginator
	p := b.SetPaginator(per, cnt)
	cnt, err = qs.Limit(p.PerPageNums, p.Offset()).RelatedSel().All(objects)
	if err != nil {
		return err
	}
	b.Data["Objects"] = objects
	b.Data["ObjectsCnt"] = cnt
	return nil
}

func (c *BaseController) GetCartCount() int {
	conn, err := redis.Dial("tcp", "47.111.181.52:6379")
	if err != nil {
		return 0
	}
	defer conn.Close()
	rep, err := conn.Do("hlen", "cart_"+strconv.Itoa(c.User.Id))
	cartCount, _ := redis.Int(rep, err)
	return cartCount
}

func ConnStr(strs ...string) string {
	var temp string
	for i := 0; i < len(strs); i++ {
		temp += strs[i]
	}
	return temp
}

func (c *BaseController) Error404() {
	c.TplName = "page/error/404.html"
}
func (c *BaseController) Error500() {
	c.TplName = "page/error/500.html"
}
